package problem111_Minimum_Depth_of_Binary_Tree;

import java.util.LinkedList;
import java.util.Queue;

import problem108_Convert_Sorted_Array_to_Binary_Search_Tree.TreeNode;

public class SolutionNonRecursive {
	public int minDepth(TreeNode root) {
		if (root == null)
			return 0;
		if (root.left == null && root.right == null)
			return 1;
		Queue<TreeNode> queue = new LinkedList<>();
		queue.add(root);
		int depth = 0;
		while (!queue.isEmpty()) {
			int size=queue.size();depth++;
			while (size-- > 0) {
				TreeNode top = queue.poll();
				if (top.left != null) {
					if (top.left.left == null && top.left.right == null) {
						return ++depth;
					}
					queue.add(top.left);
				}
				if (top.right != null) {
					if (top.right.left == null && top.right.right == null) {
						return ++depth;
					}
					queue.add(top.right);
				}
			}
		}
		return depth;
	}
}
